package com.hengxinguotong.zhihuichengjian.ui.building;

import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.BuildFileAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.EnterpriseConstructionAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.EnterpriseUserAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Build;
import com.hengxinguotong.zhihuichengjian.bean.BusinessNotify;
import com.hengxinguotong.zhihuichengjian.bean.BusinessNotifyListRes;
import com.hengxinguotong.zhihuichengjian.bean.Construction;
import com.hengxinguotong.zhihuichengjian.bean.FileBean;
import com.hengxinguotong.zhihuichengjian.bean.ReplyHistory;
import com.hengxinguotong.zhihuichengjian.bean.ReplyListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 整改详情
 * Created by liux on 2017/3/7.
 */

public class ReplyActivity extends BaseActivity implements AualityTestAddPicAdapter.OnRecyclerViewClickListener, BuildFileAdapter.OnClickListener {
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_test)
    HXTextView saveTest;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.info_ll)
    LinearLayout infoLl;
    @BindView(R.id.state_tv)
    HXTextView stateTv;
    @BindView(R.id.info_tv)
    HXTextView infoTv;
    @BindView(R.id.inspect_date)
    HXTextView inspectDate;
    @BindView(R.id.reply_date)
    HXTextView replyDate;
    @BindView(R.id.remind_date)
    HXTextView remindDate;
    @BindView(R.id.order_no_tv)
    HXTextView orderNoTv;
    @BindView(R.id.contacts_tv)
    HXTextView contactsTv;
    @BindView(R.id.contacts_moblie_tv)
    HXTextView contactsMoblieTv;
    @BindView(R.id.person_number)
    HXTextView personNumber;
    @BindView(R.id.notice_tv)
    HXTextView noticeTv;
    @BindView(R.id.test_detail_etv)
    HXTextView testDetailEtv;
    @BindView(R.id.no_data_tv)
    HXTextView noDataTv;
    @BindView(R.id.pic_rv)
    RecyclerView picRv;
    @BindView(R.id.file_rv)
    RecyclerView fileRv;
    @BindView(R.id.reply_ll)
    LinearLayout replyLl;
    @BindView(R.id.test_reply_etv)
    HXEditTextView testReplyEtv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;
    @BindView(R.id.result_ll)
    LinearLayout resultLl;
    @BindView(R.id.result_rg)
    RadioGroup resultRg;
    @BindView(R.id.pass)
    RadioButton pass;
    @BindView(R.id.notpass)
    RadioButton notpass;
    @BindView(R.id.histroy_ll)
    LinearLayout histroyLl;

    private AualityTestAddPicAdapter picAdapter;
    private AualityTestAddPicAdapter addPicAdapter;
    private AualityTestAddPicAdapter historyAdapter;
    private BuildFileAdapter fileAdapter;
    private List<FileBean> fileList;
    private List<String> paths;
    private List<String> addPaths;
    private List<String> minPaths;
    private Build build;
    private ViewHolder viewHolder;
    private List<Construction> noticeConstructions;
    private EnterpriseConstructionAdapter noticeEnterpriseAdapter;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    List<BusinessNotify> datas = (List<BusinessNotify>) msg.obj;
                    processNoticers(datas);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        build = (Build) getIntent().getSerializableExtra("build");
        setContentView(R.layout.activity_reply);
        ButterKnife.bind(this);
        if (build == null) {
            finish();
            showToast("该条信息不存在");
            return;
        }
        initView();
        getReplyHistory(build.getId());
    }

    private void initView() {
        getUserList(build.getId());//获取告知人列表
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(this);
        linearLayoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        switch (build.getCorrectiveStatus()) {
            case 1:
                tvTitleName.setText("待回复");
                if (SPUtil.getString(this, "userId").equals(build.getContactId())) {
                    saveTest.setVisibility(View.VISIBLE);
                    replyLl.setVisibility(View.VISIBLE);
                }else {
                    saveTest.setVisibility(View.GONE);
                    replyLl.setVisibility(View.GONE);
                }
                resultLl.setVisibility(View.GONE);
                stateTv.setText("待回复");
                stateTv.setTextColor(getResources().getColor(R.color.color_4dcee9));
                break;
            case 2:
                tvTitleName.setText("待复检");
                if (SPUtil.getString(this, "userId").equals(build.getCreateBy())) {
                    saveTest.setVisibility(View.VISIBLE);
                    replyLl.setVisibility(View.VISIBLE);
                    resultLl.setVisibility(View.VISIBLE);
                }else {
                    saveTest.setVisibility(View.GONE);
                    replyLl.setVisibility(View.GONE);
                    resultLl.setVisibility(View.GONE);
                }
                stateTv.setText("待复检");
                stateTv.setTextColor(getResources().getColor(R.color.color_ed8d70));
                break;
            case 3:
                tvTitleName.setText("复检不通过");
                if (SPUtil.getString(this, "userId").equals(build.getContactId())) {
                    saveTest.setVisibility(View.VISIBLE);
                    replyLl.setVisibility(View.VISIBLE);
                }else {
                    saveTest.setVisibility(View.GONE);
                    replyLl.setVisibility(View.GONE);
                }
                resultLl.setVisibility(View.GONE);
                stateTv.setText("复检不通过");
                stateTv.setTextColor(getResources().getColor(R.color.color_f3a183));
                break;
            case 4:
                tvTitleName.setText("已完成");
                saveTest.setVisibility(View.GONE);
                replyLl.setVisibility(View.GONE);
                resultLl.setVisibility(View.GONE);
                stateTv.setText("已完成");
                stateTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                break;
        }
        inspectDate.setText(build.getInspectDate());
        replyDate.setText(build.getDeadlineReplyDate());
        remindDate.setText(build.getWarningReminderDate());
        orderNoTv.setText(build.getOrderNo());
        contactsTv.setText(build.getContactName());
        testDetailEtv.setText(build.getItems());
        if((build.getPicList() == null || build.getPicList().size() == 0) && (build.getFileList() == null || build.getFileList().size() == 0)){
            noDataTv.setVisibility(View.VISIBLE);
        }else {
            noDataTv.setVisibility(View.GONE);
            if(build.getFileList() != null && build.getFileList().size() > 0){
                fileRv.setLayoutManager(linearLayoutManager2);
                fileList = build.getFileList();
                fileAdapter = new BuildFileAdapter(this, fileList);
                fileAdapter.setOnClickListener(this);
                fileRv.setAdapter(fileAdapter);
            }
            if (build.getPicList() != null && build.getPicList().size() > 0) {
                picRv.setLayoutManager(linearLayoutManager1);
                paths = build.getPicList();
                picAdapter = new AualityTestAddPicAdapter(this, paths, new AualityTestAddPicAdapter.OnRecyclerViewClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {

                    }

                    @Override
                    public void onClick(View v) {
                    }
                }, false);
                picRv.setAdapter(picAdapter);
            }
        }

        addPicRv.setLayoutManager(getLinearLayoutManager());
        addPaths = new ArrayList<String>();
        addPaths.add(Utils.ADDPIC);
        addPicAdapter = new AualityTestAddPicAdapter(this, addPaths, this, true);
        addPicRv.setAdapter(addPicAdapter);
    }

    private  EnterpriseUserAdapter.OnChildHeadClickListener headClick = new EnterpriseUserAdapter.OnChildHeadClickListener() {
        @Override
        public void onChildHeadClick(int position, int childPosition) {
            String headPotrait = noticeConstructions.get(position).getUserList().get(childPosition).getHeadPortrait();
            if(!Utils.isEmpty(headPotrait)){
                List<String> picList = new ArrayList<>();
                picList.add(headPotrait);
                TaskBigImgActivity.startActivity(ReplyActivity.this, (ArrayList<String>) picList, position);
            }
        }
    };

    private LinearLayoutManager getVerticalLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        return linearLayoutManager;
    }

    private void getEnterpriseUserList(String inspectionId) {
        Utils.requestData(null, this, "/build/queryBusinessNotifyByInspectionId/" + SPUtil.getString(this, "uuid") + "?inspectionId=" + inspectionId, null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    BusinessNotifyListRes res = new Gson().fromJson(json, BusinessNotifyListRes.class);
                    if(res.getStatus() == 1){
                        List<BusinessNotify> value = res.getValue();
                        Message message = mHandler.obtainMessage();
                        message.what = 0;
                        message.obj = value;
                        message.sendToTarget();
                    }else {
                        showToast(res.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void processNoticers(List<BusinessNotify> datas){
        for (BusinessNotify businessNotify:datas){
            Construction construction = new Construction();
            construction.setConstructionName(businessNotify.getConstructionName());
            List<User> userList = construction.getUserList();
            for (String name:businessNotify.getNames()){
                User user = new User();
                user.setName(name);
                userList.add(user);
            }
            noticeConstructions.add(construction);
        }
        noticeEnterpriseAdapter.setDataList(noticeConstructions);
    }

    private void getUserList(String inspectionId) {
        Utils.requestData(null, this, "/build/queryNotifyByInspectionId/" + SPUtil.getString(this, "uuid") + "?inspectionId=" + inspectionId, null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    try {
                        JSONObject object = new JSONObject(json);
                        int status = object.getInt("status");
                        String msg = object.getString("msg");
                        if(status == 1){
                            String value = object.getString("value");
                            noticeTv.setText(value);
                            if(Utils.isEmpty(value)){
                                personNumber.setText("共" + 0 + "人");
                            }else {
                                String[] users = value.split(",");
                                personNumber.setText("共" + users.length + "人");
                            }
                        }else {
                            showToast(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    @OnClick({R.id.iv_back, R.id.save_test, R.id.info_rl})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_test:
                getMinImage();
                break;
            case R.id.info_rl:
                if(infoLl.isShown()){
                    infoLl.setVisibility(View.GONE);
                    infoTv.setText("基本信息（信息已折叠，点击展开）");
                }else{
                    infoLl.setVisibility(View.VISIBLE);
                    infoTv.setText("基本信息（信息已展开，点击折叠）");
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && data != null) {
            addPaths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            addPaths.add(Utils.ADDPIC);
            if (addPicAdapter != null) {
                addPicAdapter.setPaths(addPaths);
            }
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (addPaths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(addPaths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            addPaths.remove(position);
            addPicAdapter.notifyDataSetChanged();
        }
    }

    private void submitRectification() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("inspectionId", build.getId());
        params.addBodyParameter("personId", SPUtil.getString(this, "userId"));
        switch (build.getCorrectiveStatus()) {
            case 1:
            case 3:
                params.addBodyParameter("correctiveStatus", "2");
                break;
            case 2:
                if (resultRg.getCheckedRadioButtonId() == -1) {
                    showToast("请选择处理结果");
                    return;
                }
                if (resultRg.getCheckedRadioButtonId() == R.id.pass) {
                    params.addBodyParameter("correctiveStatus", "4");
                } else if (resultRg.getCheckedRadioButtonId() == R.id.notpass) {
                    params.addBodyParameter("correctiveStatus", "3");
                }
                break;
        }
        params.addBodyParameter("remark", testReplyEtv.getEditableText().toString());
        if(minPaths.size() > 0){
            for (int i = 0; i < minPaths.size(); i++) {
                params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
            }
        }

        Utils.requestData(getResources().getString(R.string.loading), this, "/build/saveCorrective/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    int status = object.getInt("status");
                    if(status == 1){
                        showToast("提交成功");
                        setResult(ReplyListActivity.UPDATE);
                        finish();
                    }else{
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }

    private void getMinImage() {
        if (addPaths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < addPaths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(addPaths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    submitRectification();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            submitRectification();
        }
    }


    private void getReplyHistory(String inspectionId) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("inspectionId", inspectionId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, this, "/build/listCorrectiveProcess/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    ReplyListRes res = gson.fromJson(json, ReplyListRes.class);
                    if(res.getStatus() == 1){
                        for (final ReplyHistory replyHistory : res.getValue()) {
                            View convertView = LayoutInflater.from(ReplyActivity.this)
                                    .inflate(R.layout.item_submit_task, null, false);
                            viewHolder = new ViewHolder(convertView);
                            viewHolder.data.setText(replyHistory.getCreateTime());
                            viewHolder.name.setText(replyHistory.getCreateBy());
                            viewHolder.remarkTv.setText(replyHistory.getRemark());
                            switch (replyHistory.getCorrectiveStatus()){
                                case 1:
                                    viewHolder.stateTv.setText("提交任务");
                                    viewHolder.stateTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                                    viewHolder.stateIv.setImageResource(R.mipmap.already_confirmed);
                                    break;
                                case 2:
                                    viewHolder.stateTv.setText("提交复检");
                                    viewHolder.stateIv.setImageResource(R.mipmap.already_confirmed);
                                    viewHolder.stateTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                                    break;
                                case 3:
                                    viewHolder.stateTv.setText("复检不通过");
                                    viewHolder.stateTv.setTextColor(getResources().getColor(R.color.color_f1636a));
                                    viewHolder.stateIv.setImageResource(R.mipmap.canceled);
                                    break;
                                case 4:
                                    viewHolder.stateTv.setText("任务完成");
                                    viewHolder.stateIv.setImageResource(R.mipmap.already_confirmed);
                                    viewHolder.stateTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                                    break;
                            }

                            historyAdapter = new AualityTestAddPicAdapter(ReplyActivity.this, replyHistory.getPicList(), new AualityTestAddPicAdapter.OnRecyclerViewClickListener() {
                                @Override
                                public void onItemClick(View v, int position) {
                                    TaskBigImgActivity.startActivity(ReplyActivity.this, (ArrayList<String>) replyHistory.getPicList(), position);
                                }

                                @Override
                                public void onClick(View v) {
                                }
                            }, false);
                            viewHolder.picRv.setLayoutManager(getLinearLayoutManager());
                            viewHolder.picRv.setAdapter(historyAdapter);
                            histroyLl.addView(convertView);
                        }
                        histroyLl.setVisibility(View.VISIBLE);
                    }else {
                        showToast(res.getMsg());
                        histroyLl.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }

    @Override
    public void onClick(Object o) {
        FileBean fileBean = (FileBean) o;
        if(fileBean == null){
            return;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        String url = fileBean.getPath();
        intent.setData(Uri.parse(url));
        if (intent.resolveActivity(getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(getPackageManager());
            // 打印Log   ComponentName到底是什么
            Log.e("wl", "componentName = " + componentName.getClassName());
            startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            showToast("没有匹配的程序");
        }
    }

    static class ViewHolder {
        @BindView(R.id.state_iv)
        ImageView stateIv;
        @BindView(R.id.state_tv)
        HXTextView stateTv;
        @BindView(R.id.remark_tv)
        HXTextView remarkTv;
        @BindView(R.id.pic_rv)
        RecyclerView picRv;
        @BindView(R.id.name)
        HXTextView name;
        @BindView(R.id.data)
        HXTextView data;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
